package com.example.bbs.ui.view.video;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.SeekBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.example.bbs.R;
import com.example.bbs.util.DisplayUtil;
import com.example.bbs.util.ImageUtil;
import com.shuyu.gsyvideoplayer.utils.CommonUtil;
import com.shuyu.gsyvideoplayer.utils.Debuger;
import com.shuyu.gsyvideoplayer.utils.GSYVideoType;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.shuyu.gsyvideoplayer.video.base.GSYBaseVideoPlayer;

/**
 * 带封面
 * Created by guoshuyu on 2017/9/3.
 */
// https://github.com/CarGuo/GSYVideoPlayer
public class CoverVideoView extends StandardGSYVideoPlayer {

    static final int LONG_CLICK_THRESHOLD_MIN_TIME = 500;
    static final int LONG_CLICK_THRESHOLD_MAX_TIME = 10000;

    ImageView ivCoverImage;
    ClickableENPlayView cpvStart;
    String mCoverOriginUrl; // 远程的视频URL链接
    int mCoverOriginId = 0; // 本地图片资源
    String mGeneratedUri; // 由视频生成的封面，保存在本地的位置
    int mDefaultRes;
    long mActionDownTime;
    boolean mKeepingShowingTitle;
    OnLongClickListener mMyOnLongClickListener;
    OnClickListener mMyOnClickListener;

    @SuppressWarnings("unused")
    public CoverVideoView(Context context, Boolean fullFlag) {
        super(context, fullFlag);
    }

    public CoverVideoView(Context context) {
        super(context);
    }

    public CoverVideoView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void init(Context context) {
        super.init(context);
        ivCoverImage = findViewById(R.id.thumbImage);
        cpvStart = findViewById(R.id.start);

        if (mThumbImageViewLayout != null &&
                (mCurrentState == -1 || mCurrentState == CURRENT_STATE_NORMAL || mCurrentState == CURRENT_STATE_ERROR)) {
            mThumbImageViewLayout.setVisibility(VISIBLE);
        }

        getTitleTextView().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) { }
            @Override
            public void afterTextChanged(Editable s) {
                mTitle = s.toString();
            }
        });
        // 锁住高度
        cpvStart.setOnClickListener((v) -> DisplayUtil.setViewSize(this, getWidth(), getHeight()));
    }

    @Override
    public int getLayoutId() {
        return R.layout.view_cover_video;
    }

    public ImageView getCoverImageView() {
        return ivCoverImage;
    }

    public ClickableENPlayView getStartCPView() {
        return cpvStart;
    }

    public String getGeneratedUri() {
        return mGeneratedUri;
    }

    public void loadCoverImage(String url, int res) {
        mCoverOriginUrl = url;
        mDefaultRes = res;
        ClickableENPlayView cpvStart = findViewById(R.id.start);
        cpvStart.setVisibility(INVISIBLE);
        Glide.with(getContext().getApplicationContext())
                .setDefaultRequestOptions(
                        new RequestOptions()
                                .frame(1000000) // microsecond
                                .error(res)
                                .placeholder(R.drawable.video_cover_loading))
                .load(url)
                .into(new CustomTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        Bitmap bitmap = ((BitmapDrawable) resource).getBitmap();
                        setCoverBitmap(bitmap);
                        cpvStart.setVisibility(VISIBLE);
                        mGeneratedUri = ImageUtil.saveBitmapToCache(bitmap).toString();
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) { }
                });
    }

    @SuppressWarnings("SuspiciousNameCombination")
    public void setCoverBitmap(Bitmap bitmap) {
        float aspectRatio = (float) bitmap.getWidth() / bitmap.getHeight();
        Bitmap resizedBitmap;
        if (bitmap.getHeight() > bitmap.getWidth()) {
            setAutoFullWithSize(true); // 是否根据视频尺寸，自动选择竖屏全屏或者横屏全屏，这个标志为和 setLockLand 冲突
            setLockLand(false);
            if (aspectRatio > DisplayUtil.screenAspectRatio) {
                resizedBitmap = ImageUtil.resize(bitmap, DisplayUtil.screenSize.x, ImageUtil.KEEP_ASPECT_RATIO);
            } else {
                resizedBitmap = ImageUtil.resize(bitmap, ImageUtil.KEEP_ASPECT_RATIO, DisplayUtil.screenSize.y);
            }
        } else {
            setAutoFullWithSize(false);
            setLockLand(true);
            if (aspectRatio > 1f / DisplayUtil.screenAspectRatio) {
                resizedBitmap = ImageUtil.resize(bitmap, DisplayUtil.screenSize.y, ImageUtil.KEEP_ASPECT_RATIO);
            } else {
                resizedBitmap = ImageUtil.resize(bitmap, ImageUtil.KEEP_ASPECT_RATIO, DisplayUtil.screenSize.x);
            }
        }
        ivCoverImage.setImageBitmap(resizedBitmap);
    }

    public void loadCoverImage(int res) {
        ivCoverImage.setImageResource(res);
    }

    public void loadCoverImageBy(int id, int res) {
        mCoverOriginId = id;
        mDefaultRes = res;
        ivCoverImage.setImageResource(id);
    }

    @Override
    public GSYBaseVideoPlayer startWindowFullscreen(Context context, boolean actionBar, boolean statusBar) {
        GSYBaseVideoPlayer gsyBaseVideoPlayer = super.startWindowFullscreen(context, actionBar, statusBar);
        CoverVideoView sampleCoverVideo = (CoverVideoView) gsyBaseVideoPlayer;
        if(mCoverOriginUrl != null) {
            sampleCoverVideo.loadCoverImage(mCoverOriginUrl, mDefaultRes);
        } else if(mCoverOriginId != 0) {
            sampleCoverVideo.loadCoverImageBy(mCoverOriginId, mDefaultRes);
        }
        return gsyBaseVideoPlayer;
    }

    @Override
    public GSYBaseVideoPlayer showSmallVideo(Point size, boolean actionBar, boolean statusBar) {
        //下面这里替换成你自己的强制转化
        CoverVideoView coverVideoView = (CoverVideoView) super.showSmallVideo(size, actionBar, statusBar);
        coverVideoView.mStartButton.setVisibility(GONE);
        coverVideoView.mStartButton = null;
        return coverVideoView;
    }

    @Override
    protected void cloneParams(GSYBaseVideoPlayer from, GSYBaseVideoPlayer to) {
        super.cloneParams(from, to);
        CoverVideoView sf = (CoverVideoView) from;
        CoverVideoView st = (CoverVideoView) to;
        st.mShowFullAnimation = sf.mShowFullAnimation;
    }

    public void enableFullScreenManually(boolean enabled) {
        mFullscreenButton.setEnabled(enabled);
    }

    public void setKeepingShowingTitle(boolean keepingShowingTitle) {
        mKeepingShowingTitle = keepingShowingTitle;
    }

    public void setMyOnClickListener(@Nullable OnClickListener l) {
        mMyOnClickListener = l;
    }

    public void setMyOnLongClickListener(@Nullable OnLongClickListener l) {
        mMyOnLongClickListener = l;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev)
    {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            mActionDownTime = System.currentTimeMillis();
        } else if (ev.getAction() == MotionEvent.ACTION_UP) {
            long time = System.currentTimeMillis() - mActionDownTime;
            if (time < LONG_CLICK_THRESHOLD_MIN_TIME && mMyOnClickListener != null) {
                mMyOnClickListener.onClick(this);
            } else if (time < LONG_CLICK_THRESHOLD_MAX_TIME && mMyOnLongClickListener != null) {
                mMyOnLongClickListener.onLongClick(this);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 退出window层播放全屏效果
     */
    @SuppressWarnings("ResourceType")
    @Override
    protected void clearFullscreenLayout() {
        if (!mFullAnimEnd) {
            return;
        }
        mIfCurrentIsFullscreen = false;
        int delay = 0;
        // ------- ！！！如果不需要旋转屏幕，可以不调用！！！-------
        // 不需要屏幕旋转，还需要设置 setNeedOrientationUtils(false)
        if (mOrientationUtils != null) {
            delay = mOrientationUtils.backToProtVideo();
            mOrientationUtils.setEnable(false);
            if (mOrientationUtils != null) {
                mOrientationUtils.releaseListener();
                mOrientationUtils = null;
            }
        }

        if (!mShowFullAnimation) {
            delay = 0;
        }

        final ViewGroup vp = (CommonUtil.scanForActivity(getContext())).findViewById(Window.ID_ANDROID_CONTENT);
        final View oldF = vp.findViewById(getFullId());
        if (oldF != null) {
            //此处fix bug#265，推出全屏的时候，虚拟按键问题
            CoverVideoView gsyVideoPlayer = (CoverVideoView) oldF;
            gsyVideoPlayer.mIfCurrentIsFullscreen = false;
        }

        if (delay == 0) {
            backToNormal();
        } else {
            postDelayed(this::backToNormal, delay);
        }

    }


    /******************* 下方两个重载方法，在播放开始前不屏蔽封面，不需要可屏蔽 ********************/
    @Override
    public void onSurfaceUpdated(Surface surface) {
        super.onSurfaceUpdated(surface);
        if (mThumbImageViewLayout != null && mThumbImageViewLayout.getVisibility() == VISIBLE) {
            mThumbImageViewLayout.setVisibility(INVISIBLE);
        }
        if (mKeepingShowingTitle) {
            getTitleTextView().setVisibility(VISIBLE);
        }
    }

    @Override
    protected void setViewShowState(View view, int visibility) {
        if (view == mThumbImageViewLayout && visibility != VISIBLE) {
            return;
        }
        super.setViewShowState(view, visibility);
    }

    @Override
    public void onSurfaceAvailable(Surface surface) {
        super.onSurfaceAvailable(surface);
        if (GSYVideoType.getRenderType() != GSYVideoType.TEXTURE) {
            if (mThumbImageViewLayout != null && mThumbImageViewLayout.getVisibility() == VISIBLE) {
                mThumbImageViewLayout.setVisibility(INVISIBLE);
            }
            if (mKeepingShowingTitle) {
                getTitleTextView().setVisibility(VISIBLE);
            }
        }
    }

    /******************* 下方重载方法，在播放开始不显示底部进度和按键，不需要可屏蔽 ********************/

    protected boolean byStartedClick;

    @Override
    protected void onClickUiToggle() {
        if (mIfCurrentIsFullscreen && mLockCurScreen && mNeedLockFull) {
            setViewShowState(mLockScreen, VISIBLE);
            return;
        }
        byStartedClick = true;
        super.onClickUiToggle();
    }

    @Override
    protected void changeUiToNormal() {
        super.changeUiToNormal();
        byStartedClick = false;
    }

    @Override
    protected void changeUiToPreparingShow() {
        super.changeUiToPreparingShow();
        Debuger.printfLog("Sample changeUiToPreparingShow");
        setViewShowState(mBottomContainer, INVISIBLE);
        setViewShowState(mStartButton, INVISIBLE);
    }

    @Override
    protected void changeUiToPlayingBufferingShow() {
        super.changeUiToPlayingBufferingShow();
        Debuger.printfLog("Sample changeUiToPlayingBufferingShow");
        if (!byStartedClick) {
            setViewShowState(mBottomContainer, INVISIBLE);
            setViewShowState(mStartButton, INVISIBLE);
        }
    }

    @Override
    protected void changeUiToPlayingShow() {
        super.changeUiToPlayingShow();
        Debuger.printfLog("Sample changeUiToPlayingShow");
        if (!byStartedClick) {
            setViewShowState(mBottomContainer, INVISIBLE);
            setViewShowState(mStartButton, INVISIBLE);
        }
    }

    @Override
    public void startAfterPrepared() {
        super.startAfterPrepared();
        Debuger.printfLog("Sample startAfterPrepared");
        setViewShowState(mBottomContainer, INVISIBLE);
        setViewShowState(mStartButton, INVISIBLE);
        setViewShowState(mBottomProgressBar, VISIBLE);
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        byStartedClick = true;
        super.onStartTrackingTouch(seekBar);
    }
}
